<?php
/**
 * Created by PhpStorm.
 * User: Sojo
 * Date: 2016/6/25
 * Time: 20:07
 */
namespace App\Http\Admin\Process\Models;

use Framework\BaseClass\Http\Admin\Model;
use App\Eloquent\Admin\Process as EloquentProcess;
use App\Eloquent\Admin\ProcessMenu;

class Process extends Model
{
    /**
     * Description:获取工序列表
     * User: zhuyujun
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getProcessList()
    {
        $processList = EloquentProcess::all();
        //调整数据的值
        foreach ($processList as $row) {
            //创建时间(通过时间戳转换为字符串)
            $row->created_str = $row->created_at->formatLocalized('%Y%m%d %H:%M:%S');
        }
        return $processList;
    }

    /**
     * Description:获取工序id对应的工序信息
     * User: zhuyujun
     * @param $id
     * @return string
     */
    public function getRowById($id)
    {
        return '';

    }

    public function insert($input)
    {
        $eloquentProcess = EloquentProcess::firstOrNew(['title' => $input['title']]);
        if ($eloquentProcess->id) xThrow(ERR_CLIENT_USER_ALREADY_EXISTS);

        $insertRow = [
            'title' => $input['title'],
            'table' => $input['table'],
        ];

        $eloquentProcess->fill($insertRow);
        return $eloquentProcess->save();
    }


    public function getMenuListByPermissionAssignment($roleId)
    {
        $roleMenuIds = RoleMenu::where('admin_role_id', $roleId)->get()->pluck('admin_menu_id')->toArray();

        $menuList = EloquentMenu::all();

        $topMenuIds = [];
        foreach ($menuList as $menu) {
            if ($menu->pid == 0) $topMenuIds[] = $menu->id;
        }

        $leftMenuIds = [];
        foreach ($menuList as $menu) {
            if (in_array($menu->pid, $topMenuIds)) $leftMenuIds[] = $menu->id;
        }

        $filterMenuIds = array_merge($topMenuIds, $leftMenuIds);
        $returnData = [];
        foreach ($menuList as $key => $menu) {
            if (!in_array($menu->id, $filterMenuIds)) {
                $menu->permission = (in_array($menu->id, $roleMenuIds)) ? 1 : 0;
                $menu->role_id = $roleId;
                $returnData[] = $menu->toArray();
            }
        }

        return $returnData;
    }
}